<template>
    <div class="da-login">
        <div class="da-login-form">
            <div class="da-login-logo-wrapper">
                <div class="da-login-logo">
                    <span class="da-logo-devui">
                        <img src="/devui-logo.svg" alt="YiHe-Logo" />
                    </span>
                    <span class="da-text">{{ sysStore.title }}</span>
                </div>
            </div>
            <div class="da-login-ways">
                <el-form
                    ref="formRef"
                    :label-position="'left'"
                    label-width="30%"
                    :model="formModel"
                    :rules="formRules"
                >
                    <el-form-item prop="userAccount" label="用户名">
                        <el-input
                            v-model="formModel.userAccount"
                            placeholder="请输入用户名"
                            :prefix-icon="User"
                        ></el-input>
                    </el-form-item>
                    <el-form-item prop="userAccountPassword" label="密码">
                        <el-input
                            v-model="formModel.userAccountPassword"
                            show-password
                            placeholder="请输入密码"
                            :prefix-icon="Lock"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        prop="captchaText"
                        label="验证码"
                    >
                        <el-input
                            v-model="formModel.captchaText"
                            type="text"
                            :prefix-icon="WindPower"
                        ></el-input>
                        <div v-html="captchaData" @click="getCaptcha"></div>
                    </el-form-item>
                </el-form>
                <div class="da-login-options">
                    <div class="da-auto-login">
                        <el-switch v-model="formModel.rememberme"></el-switch>
                        <span
                            class="da-auto-login-text"
                            style="margin-left: 8px"
                            >记住我</span
                        >
                    </div>
                </div>
                <el-button @click="onSave" round size="default" type="primary">
                    登录
                </el-button>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts" name="Login">
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { User, Lock, WindPower } from '@element-plus/icons-vue';
import { useSysStore } from '@/store/sys';
import { useAppStore } from '@/store/app';
import type { ValidateFieldsError } from 'async-validator';
import { Md5 } from 'ts-md5';

import { Request } from '@/app/request';
import router from '@/router';
import { FuncURLMap, GenFuncUrlMap } from '@/common/const';

const sysStore = useSysStore();
const appStore = useAppStore();

const formRef = ref<FormInstance>();

type user = {
    userAccount?: string;
    userAccountPassword?: string;
    captchaText?: string;
    rememberme?: boolean;
};
const captchaData = ref('');
const formModel = reactive<user>({});
const formRules = reactive<FormRules<user>>({
    userAccount: [
        { required: true, message: '用户名不能为空', trigger: 'blur' }
    ],
    userAccountPassword: [
        { required: true, message: '密码不能为空',  trigger: 'blur', }
    ],
    captchaText: [
        {required: true, message: '验证码不能为空', trigger: 'blur'}
    ]
});
onMounted(() => {
    formModel.userAccount = localStorage.getItem('userAccount') || '';
    formModel.rememberme = formModel.userAccount.length > 0 ? true : false;
    sysStore.oper.id = 0;
    sysStore.oper.name = '';
    getCaptcha();
});
const getCaptcha = async () => {
    const req = new Request('验证码');
    const r = await req.get();
    captchaData.value = r.obj;
};
const onSave = async () => {
    /* router.push({
       name: 'main'
    }); */
    /* location.hash = '#/main'; */
    const formValid = await formRef.value?.validate(
        (_isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
        },
    );

    if (formValid) {
        // 发送登录请求
        sysStore.oper = {};
        const userPass = Md5.hashStr(
            (formModel.userAccountPassword as string) + '8',
        ) as string;
        const req = new Request('登入', {
            oper: formModel.userAccount as string,
            pw: userPass,
            captcha: formModel.captchaText as string,
        });
        const r = await req.post();
        if (r.code > 100) {
            // sysStore.oper.name = formModel.userAccount as string;
            sysStore.oper.id = r.obj.id;
            sysStore.oper.name = r.obj.name;
            const regex = new RegExp(
                '(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9]).{8,30}',
            );
            if (!regex.test(formModel.userAccountPassword as string)) {
                sysStore.oper.pwflag = false;
                ElMessage.info('密码强度低，请修改密码后再登录!');
            } else {
                sysStore.oper.pwflag = true;
            }

            if (formModel.rememberme) {
                localStorage.setItem('userAccount', sysStore.oper!.name!);
            } else {
                localStorage.removeItem('userAccount');
            }
            Object.keys(FuncURLMap).forEach(key => {
                if (!Reflect.has(GenFuncUrlMap, key)) {
                    Reflect.deleteProperty(FuncURLMap, key);
                }
            });
            // Object.assign(FuncURLMap, GenFuncUrlMap);
            Object.assign(FuncURLMap, r.ext);
            appStore.initData();
            // console.log(FuncURLMap);
            
            router.push({
                name: 'main',
            });
        } else {
            getCaptcha();
        }
    }
};
</script>
<style lang="scss" scoped>

.da-login {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: end;
    align-items: self-start;
    background-image: url('img_log.png');
    
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;

    .da-login-form {
        flex-basis: 400px;
        // width: 400px;
        font-size: 16px;
        // padding: 0 24px;
        margin-top: 5%;
        margin-right: 5%;
        .da-login-logo-wrapper {
            margin-bottom: 5%;
            display: flex;
            flex-direction: column;

            .da-login-logo {
                display: flex;
                align-items: center;
                justify-content: center;

                .da-logo-devui {
                    img {
                        width: 60px;
                        height: 60px;
                    }
                }

                .da-text {
                    color: rgb(37, 43, 58);
                    font-size: 36px;
                    font-family: cursive;
                    margin-left: 16px;
                    font-weight: 600;
                }
            }
        }

        .da-login-ways {
            display: flex;
            flex-direction: column;
        }

        .da-login-options {
            display: flex;
            justify-content: space-between;
            margin-bottom: 32px;

            .auto-login-text {
                margin-left: 8px;
            }
        }
    }
}
</style>
